import cv2 as cv
import copy
from matplotlib import pyplot as plt

imgPath = "lena.jpg"
img = cv.imread(imgPath)

cv.imshow("lena", img)
cv.moveWindow("lena", 0, 40)
# 题目一
# 均值滤波
img_blur = cv.blur(img, (3, 3))
cv.imshow("lena_blur", img_blur)
cv.moveWindow("lena_blur", 550, 40)
# 高斯滤波
img_gblur = cv.GaussianBlur(img, (9, 9), 0)
cv.imshow("lena_gblur", img_gblur)
cv.moveWindow("lena_gblur", 1100, 40)
# 中值滤波
img_mblur = cv.medianBlur(img, 9)
cv.imshow("lena_mblur", img_mblur)
cv.moveWindow("lena_mblur", 1650, 40)
# 题目二
# sobel
sobelx = cv.Sobel(img, cv.CV_64F, 1, 0)
sobely = cv.Sobel(img, cv.CV_64F, 0, 1)
absx = cv.convertScaleAbs(sobelx)
absy = cv.convertScaleAbs(sobely)
img_sobel = cv.addWeighted(absx, 0.5, absy, 0.5, 0)
#cv.imshow("sobelx", sobelx)
#cv.imshow("sobely", sobely)
cv.imshow("sobel", img_sobel)
cv.moveWindow("sobel", 550, 600)
# canny 算子检测
img_canny = cv.Canny(img, 50, 150)
cv.imshow("canny", img_canny)
cv.moveWindow("canny", 1100, 600)
cv.waitKey()
# 题目三

img_rice_path = "rice.png"
img_rice = cv.imread(img_rice_path)

plt.hist(img_rice.ravel(), 256, [0, 256])
plt.show()
rice_gray = cv.cvtColor(img_rice, cv.COLOR_BGR2GRAY)
# 大津算法阈值化
_, bw = cv.threshold(rice_gray, 0, 0xff, cv.THRESH_OTSU)
# 去除噪声
element = cv.getStructuringElement(cv.MORPH_CROSS, (3, 3))
bw = cv.morphologyEx(bw, cv.MORPH_OPEN, element)

seg = copy.deepcopy(bw)
#图像分割
cnts, hier = cv.findContours(seg, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

count = 0

for i in range(len(cnts), 0, -1):
    c = cnts[i - 1]
    # 求分割出来的面积
    area = cv.contourArea(c)
    # 小于10 认为是噪声
    if area < 10:
        continue
    count = count + 1
    print("blob", i, " : ", area)
    #求出包围矩形
    #x, y, w, h = cv.minAreaRect(c)
    x, y, w, h = cv.boundingRect(c)
    #画出矩形
    cv.rectangle(img_rice, (x, y), (x + w, y + h), (0, 0, 0xff), 1)
    cv.putText(img_rice, str(count), (x, y), cv.FONT_HERSHEY_PLAIN, 0.5,
               (0, 0XFF, 0))
print("米粒数量：", count)
cv.imshow("img_rice", img_rice)
cv.moveWindow("img_rice", 0, 600)
cv.imshow("threshold_rice", bw)
cv.moveWindow("threshold_rice", 0, 1000)
cv.waitKey()
cv.destroyAllWindows()
plt.close()
